package com.example.lijuan.myapplication.Client;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.atomic.AtomicBoolean;

public class SocketClient {

    static Socket socket;
    AtomicBoolean started = new AtomicBoolean(false);
    private InetSocketAddress isa;

    public SocketClient() {

        try {
            isa = new InetSocketAddress(InetAddress.getByName(Configuration.SERVER_HOST), Configuration.SERVER_PORT);
        } catch (UnknownHostException e) {
            isa = new InetSocketAddress(Configuration.SERVER_HOST, Configuration.SERVER_PORT);
        }
    }

    public void start() {
        try {
            socket = new Socket();

            socket.connect(isa, 3000);

            started.set(true);
        } catch (Exception e) {
            stop();
        }
    }

    public void stop(){
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e1) {

            }
            socket = null;
        }
        started.set(false);
    }


    public void send(byte[] data) {
        if (!started.get()){
            start();
        }
        try {
            OutputStream ou = socket.getOutputStream();
            ou.write(data);
            ou.flush();
        } catch (IOException e) {
            stop();
        }
    }

}




